<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/20 10:48
 * Desc: 商城
 */
trait Trait_Api_Malls
{
    /**
     * 首页分类
     * @return array
     */
    public function get_index_classify()
    {
        $list = DB::select()->from('malls_classify')
            ->where('pid', '=', 0)
            ->and_where('isopen', '=', 1)
            ->order_by(DB::expr('IFNULL(displayorder,9999)'), 'asc')
            ->execute()
            ->as_array();
        $data = array();
        foreach ($list as &$v) {
            $data[] = array(
                'litpic' => $this->img_url($v['litpic']),
                'id' => $v['id'],
                'title' => $v['attrname'],
            );
        }

        return $data;
    }

    /**
     *  获取首页最新产品
     * @return mixed|null
     */
    public function get_new_product()
    {
        $data = Model_Api_V2_Malls::query(array('flag' => 'new', 'row' => 5));
        foreach ($data as &$item) {
            $item['litpic'] = $this->img_url($item['litpic'], 210, 210);
        }
        return $data;
    }

    /**
     * 首页热门
     * @return mixed|null
     */
    public function get_hot_product()
    {
        $data = Model_Api_V2_Malls::query(array('flag' => 'good'));
        foreach ($data as &$item) {
            $item['litpic'] = $this->img_url($item['litpic'], 340, 340);
        }
        return $data;
    }

    /**
     * 分类
     * @return array
     */
    public function get_classify()
    {
        $data = array();
        $list = Model_Api_V2_Malls::get_classify_by_pid(0);
        foreach ($list as $v) {
            $title = $v['attrname'];
            $info  = Model_Api_V2_Malls::get_classify_by_pid($v['id']);
            foreach ($info as &$vv) {
                $vv['litpic'] = $this->img_url($vv['litpic']);
            }
            $data[] = array(
                'title' => $title,
                'id' => $v['id'],
                'info' => $info
            );
        }

        return $data;
    }

    /**
     * 获取购物车数量
     * @param $mid
     * @param $params
     * @return int
     */
    public function get_car_num($mid, $params = array())
    {
        $product_id = Arr::get($params, 'product_id', '');
        $builder    = DB::select()
            ->from('malls_cars')
            ->where('mid', '=', $mid)
            ->and_where('type', '=', 2);
        if ($product_id) {
            $builder->and_where('malls_id', '=', $product_id);
        }
        return $builder->execute()->count();
    }

    /**
     * 加入购物车
     * @param $mid
     * @param $params
     * @return array
     * @throws Kohana_Exception
     * @throws Exception
     */
    public function add_car($mid, $params)
    {

        /**
         * @var $product_id
         * @var $suit_id
         * @var $num
         * @var $type
         */
        extract($params);

        $check = Model_Api_V2_Malls::check_malls_order($product_id, $suit_id, $num, $mid, $type);

        if (!$check['status']) {
            $msg = $check['msg'] ?? '添加失败';
            throw new Exception($msg);
        }

        $res = DB::select()
            ->from("malls_cars")
            ->where("malls_id", "=", $product_id)
            ->and_where("suit_id", "=", $suit_id)
            ->and_where("mid", "=", $mid)
            ->and_where("type", "=", 2)
            ->execute()
            ->current();

        $data = array(
            'malls_id' => $product_id,
            'suit_id' => $suit_id,
            'mid' => $mid,
            'num' => $check['num'],
            'modtime' => time(),
            'title' => $check['info']['title'],
            'litpic' => $check['info']['litpic'],
            'type' => $type
        );
        if (!$res || $type == 1) { // 不存在 或者 为购买
            $data['addtime'] = time();
            list($id, $row) = DB::insert('malls_cars', array_keys($data))->values(array_values($data))->execute();
            if (!$id) {
                throw new Exception('添加失败');
            }
        } else { // 更新
            $id = $res['id'];
            DB::update('malls_cars')
                ->set($data)
                ->where("malls_id", "=", $product_id)
                ->and_where("suit_id", "=", $suit_id)
                ->and_where("mid", "=", $mid)
                ->execute();
        }

        return array(
            'id' => $id
        );
    }


    /**
     * 购物车列表
     * @param $mid
     * @return array
     */
    public function get_car_list($mid)
    {

        $list = DB::select('mc.id', 'mc.malls_id', 'mc.suit_id', 'mc.num', 'mc.title', 'mc.litpic', 'sm.need_kuaidi')
            ->from(array('malls_cars', 'mc'))
            ->join(array('malls', 'sm'), 'inner')
            ->on('mc.malls_id', '=', DB::expr('sline_sm.id'))
            ->where('mc.mid', '=', $mid)
            ->and_where('mc.type', '=', 2)
            ->order_by('mc.modtime', 'desc')
            ->execute()
            ->as_array();

        foreach ($list as &$v) {// 检查购物车里面是否可以下单
            $check = Model_Api_V2_Malls::check_malls_car($v['malls_id'], $v['suit_id'], $v['num']);
            if ($check['status'] == 201) {
                $v['status'] = 201; //失效 需要删除
            } else if ($check['status'] == 202) {
                $v['status'] = 202; //库存不足 需要修改库存
            } else {
                $v['status'] = 200;
            }
            $types    = Model_Api_V2_Malls::suit($v['malls_id']);
            $new_type = array();
            foreach ($types as $k => $vv) {
                if ($vv['id'] == $v['suit_id']) {
                    $v['index'] = $k;
                }
                $type_item  = array(
                    'name' => $vv['suitname'],
                    'id' => $vv['id'],
                    'src' => $this->img_url($vv['litpic']),
                    'price' => $vv['price'],
                    'inventory' => $vv['number'], //库存
                    'maxNum' => $vv['max_number'], //限购
                    'sellprice' => $vv['sellprice']
                );
                $new_type[] = $type_item;
            }

            $v['types']     = $new_type;
            $v['number']    = $v['num'];
            $v['price']     = $check['price'];
            $v['suit_name'] = $check['suit_name'];
            $v['litpic']    = $this->img_url($v['litpic']);
        }

        return array(
            'list' => $list
        );
    }


    /**
     * 删除购物车
     * @param $mid
     * @param $car_id
     * @return true[]
     */
    public function del_car($mid, $car_id)
    {
        DB::delete("malls_cars")
            ->where("mid", "=", $mid)
            ->and_where('id', 'in', explode(',', $car_id))
            ->execute();
        return array(
            'status' => true
        );
    }

    /**
     * 切换购物车套餐
     * @param $mid
     * @param $params
     * @return array
     * @throws Exception
     * @throws Kohana_Exception
     */
    public function change_car_list($mid, $params)
    {
        /**
         * @var $car_id
         * @var $suit_id
         */
        extract($params);

        $car_info = DB::select()
            ->from("malls_cars")
            ->where("id", "=", $car_id)
            ->and_where("mid", "=", $mid)
            ->execute()
            ->current();
        if (!$car_info) {
            throw new Exception('提交信息有误');
        }

        // 不相等时才执行套餐切换
        $res = array();
        if ($car_info['suit_id'] != $suit_id) {

            $num        = $car_info['num'];
            $product_id = $car_info['malls_id'];

            $add_params = array(
                'product_id' => $product_id,
                'suit_id' => $suit_id,
                'num' => $num,
                'mid' => $mid,
                'type' => 2,
            );
            $res        = $this->add_car($mid, $add_params);

            // 移除原购物车商品
            $this->del_car($mid, $car_id);
        }

        return $res;
    }

    /**
     * 获取快递费用
     * @param $mid
     * @param $params
     * @return array
     */
    public function get_express_fee($mid, $params)
    {
        /**
         * @var $car_id
         * @var $address_id
         */
        extract($params);

        $param = array(
            'car_id' => $car_id,
            'addressid' => $address_id,
            'userid' => $mid
        );
        return Model_Api_V2_Malls::get_express_fee($param);
    }

    /**
     * 订单详情
     * @param $mid
     * @param $params
     * @return array
     * @throws Exception
     */
    public function get_order_detail($mid, $params)
    {
        /**
         * @var $order_id
         */
        extract($params);

        //主订单
        $ordersn = DB::select('ordersn')
            ->from('member_order')
            ->where('id', '=', $order_id)
            ->and_where('memberid', '=', $mid)
            ->execute()
            ->get('ordersn');
        if (empty($ordersn)) {
            throw new Exception('订单不存在');
        }

        $row = Model_Member_Order::order_info($ordersn, $mid);

        // 子订单
        $child = DB::select("ordersn")
            ->from("member_order")
            ->where("pid", "=", $order_id)
            ->execute()
            ->as_array();
        $c_arr = array();
        foreach ($child as $vv) {
            $item  = array();
            $c_row = Model_Member_Order::order_info($vv['ordersn'], $mid);
            //封面图
            $item['litpic']        = $this->img_url($c_row['litpic']);
            $item['num']           = $c_row['dingnum'];
            $item['price']         = $c_row['price'];
            $item['ispinlun']      = $c_row['ispinlun'];
            $item['status']        = $c_row['status'];
            $item['id']            = $c_row['id'];
            $item['productautoid'] = $c_row['productautoid'];
            $item['subname']       = $c_row['suit_name'];
            $item['productname']   = $c_row['productname'];
            $c_arr[]               = $item;
        }

        $row['payprice']   = Currency_Tool::price($row['payprice']);
        $totalprice        = $row['totalprice'] - $row['express_total_price']; // 扣减运费
        $row['totalprice'] = Currency_Tool::price($totalprice);

        $row['c_order']    = $c_arr;
        $status            = DB::select()
            ->from('malls_order_status')
            ->where('status', '=', $row['status'])
            ->and_where('is_show', '=', 1)
            ->execute()
            ->current();
        $row['statusname'] = $status['status_name'];

        if ($row['receiver_address_id']) {
            $receiver_address        = DB::select()
                ->from('member_address')
                ->where('id', '=', $row['receiver_address_id'])
                ->execute()
                ->current();
            $row['receiver_address'] = $receiver_address;

        }
        $row = Pay_Online_Refund::get_refund_info($row);

        //快递信息
        $express_info = DB::select("express_company_name", "express_code", "end_time")
            ->from("malls_order_express")
            ->where("ordersn", "=", $row['ordersn'])
            ->execute()
            ->current();
        if ($express_info) {
            $auto_time = $express_info['end_time'] - time();
            if ($auto_time > 0) {
                $day    = floor($auto_time / 86400);
                $hour   = floor(($auto_time - $day * 86400) / 3600);
                $minute = floor(($auto_time - $day * 86400 - 3600 * $hour) / 60);

                $day_s    = $day > 0 ? $day . '天' : '';
                $hour_s   = $hour > 0 ? $hour . '小时' : '';
                $minute_s = $minute > 0 ? $minute . '分' : '';

                $auto_str                 = $day_s . $hour_s . $minute_s;
                $express_info['auto_str'] = $auto_str;
            }
        }

        $suit = DB::select()
            ->from('malls_suit')
            ->where('id', '=', $row['suitid'])
            ->execute()
            ->current();

        $suit['express_template'] = DB::select()
            ->from('express_template')
            ->where('id', '=', $suit['freightid'])
            ->execute()
            ->current();

        $row['express']           = $express_info;
        $row['addtime_fmt']       = date('Y-m-d H:i:s', $row['addtime']);
        $row['paytime']           = $row['paytime'] ? date('Y-m-d H:i:s', $row['paytime']) : '';

        $row['card_pay'] = false;
        if (St_Functions::is_normal_app_install('system_card')) {
            $sub_order = DB::select()->from('member_order')->where("pid={$row['id']}")->execute()->current();
            $is_exist  = DB::select()->from('card_member_reservation_record')->where("order_sn='{$sub_order['ordersn']}'")->execute()->current();
            if ($is_exist) {
                $row['card_pay'] = true;
            }
        }

        return $row;
    }
}